package wrapper

import (
	"context"
	"github.com/micro/go-micro/v2/client"
	"github.com/micro/go-micro/v2/metadata"
	"kop/framework/errors"
	"runtime"
)

type clientLogWrapper struct {
	client.Client
}

func (l *clientLogWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, _ ...client.CallOption) error {

	pc, _, _, _ := runtime.Caller(1)
	var name1 = runtime.FuncForPC(pc).Name()

	pc, _, _, _ = runtime.Caller(2)
	var name2 = runtime.FuncForPC(pc).Name()

	pc, _, _, _ = runtime.Caller(3)
	var name3 = runtime.FuncForPC(pc).Name()

	pc, _, _, _ = runtime.Caller(4)
	var name4 = runtime.FuncForPC(pc).Name()

	pc, _, _, _ = runtime.Caller(5)
	var name5 = runtime.FuncForPC(pc).Name()

	md, _ := metadata.FromContext(ctx)
	if md == nil {
		md = make(metadata.Metadata)
	}
	md["Source"] = name5 + "->" + name4 + "->" + name3 + "->" + name2 + "->" + name1
	ctx = metadata.NewContext(ctx, md)

	if err := l.Client.Call(ctx, req, rsp); err != nil {

		err2 := errors.Parse(err)
		err2.Detail = req.Endpoint() + ": " + err2.Detail
		return err2
	}

	return nil
}

func ClientLogWrapper(c client.Client) client.Client {
	return &clientLogWrapper{c}
}
